package com.atguigu.test5;

/**
 * @author 路飞
 * @date 2024/3/28 15:36
 * @description 13.	请用wait()和notify()方法编写一个生产者消费者设计模式程序?
 */
public class Exer13 {
    public static void main(String[] args) {
        Computer computer = new Computer();
        Producer producer = new Producer(computer);
        Consumer consumer = new Consumer(computer);
        producer.setName("producer");
        consumer.setName("consumer");

        producer.start();
        consumer.start();
    }
}

class Computer {
    boolean isProducer = true;

    String mainBoard;

    String screen;

    public Computer() {
    }

    public Computer(String mainBoard, String screen) {
        this.mainBoard = mainBoard;
        this.screen = screen;
    }

    public String getMainBoard() {
        return mainBoard;
    }

    public void setMainBoard(String mainBoard) {
        this.mainBoard = mainBoard;
    }

    public String getScreen() {
        return screen;
    }

    public void setScreen(String screen) {
        this.screen = screen;
    }

    public boolean isProducer() {
        return isProducer;
    }

    public void setProducer(boolean producer) {
        isProducer = producer;
    }

    @Override
    public String toString() {
        return "Computer{" +
                ", mainBoard='" + mainBoard + '\'' +
                ", screen='" + screen + '\'' +
                '}';
    }
}

class Producer extends Thread {
    private final Computer computer;

    public Producer(Computer computer) {
        this.computer = computer;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            synchronized (computer) {
                if (!computer.isProducer) {
                    try {
                        computer.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.println(Thread.currentThread().getName() + "开始生产第" + i + "台电脑");
                computer.setMainBoard("华硕" + i);
                computer.setScreen("灵蛇" + i);
                computer.notify();
                computer.setProducer(false);
            }
        }
    }
}

class Consumer extends Thread {
    private final Computer computer;

    public Consumer(Computer computer) {
        this.computer = computer;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            synchronized (computer) {
                if (computer.isProducer) {
                    try {
                        computer.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.println(Thread.currentThread().getName() + "开始消费第" + i + "台" + computer);
                computer.setProducer(true);
                computer.notify();
            }
        }
    }
}


